package com.zw.se2.general;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttPublish {


    public static final String TOPIC = "foo";

    private MqttClient client;
    private MqttTopic topic;
    private String userName = "DataExpress";
    private String passWord = "DataExpress";


    public MqttPublish(String host, String clientid) throws MqttException {
        //MemoryPersistence����clientid�ı�����ʽ��Ĭ��Ϊ���ڴ汣��
        client = new MqttClient("tcp://" + host + ":1883", clientid, new MemoryPersistence());
        connect();
    }

    private void connect() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());
        // ���ó�ʱʱ��
        options.setConnectionTimeout(10);
        // ���ûỰ����ʱ��
        options.setKeepAliveInterval(20);
        try {
            client.setCallback(new MqttCallback() {
                public void connectionLost(Throwable throwable) {

                }
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {

                }
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                }
            });
            client.connect(options);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void publish(MqttMessage message) throws MqttException {
        MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion();
//        System.out.println(token.isComplete()+"========");
    }


    public void publish(String Topic, String msg) throws MqttException {
        topic = client.getTopic(Topic);
        MqttMessage message = new MqttMessage();
        message.setQos(1);
        message.setRetained(true);
        message.setPayload(msg.getBytes());
        MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion();
    }


}
